const express = require('express');
const fs = require('fs');
const path = require('path');
const querystring = require('querystring');

const tool = require('./tool.js')
const user = require('./model/User.js');

const router = express.Router();

// 用于储存通信实例socket与用户名之间的对应关系
router.socketToUser = new Map();
router.userToSocket = new Map();

router.post('/app/:userName', (req, res) => {
    const userName = req.params.userName;
    user.status(userName, (status) => {
        if (status) {
            if (tool.isFile(path.join(__dirname, `user/user_${userName}/app.json`))) {
                res.setHeader('Content-Type', 'application/json');
                fs.createReadStream(path.join(__dirname, `user/user_${userName}/app.json`)).pipe(res);
            } else {
                res.setHeader('Content-Type', 'application/json');
                fs.createReadStream(path.join(__dirname, 'data/app-default.json')).pipe(res);
            }
        } else {
            res.sendStatus(403);
        }
    });
});

router.post('/app/:userName/restore', (req, res) => {
    const userName = req.params.userName;
    user.status(userName, (status) => {
        if (status) {
            fs.readFile(path.join(__dirname, 'data/app-default.json'), (err, data) => {
                if (err) {
                    res.end();
                }
                fs.writeFile(path.join(__dirname, `user/user_${userName}/app.json`), data.toString('utf-8'), () => {
                    res.end();
                });
            });
            // 删除用户文件夹
            fs.rm(path.join(__dirname, `user/user_${userName}/files`), {force: true, recursive: true}, () => {});
            // 清空socket记录
            router.socketToUser.delete(router.userToSocket.get(userName));
            router.userToSocket.delete(userName);
        } else {
            res.sendStatus(403);
        }
    });
});

router.post('/app/:userName/addApp/:projectName', (req, res) => {
    const userName = req.params.userName;
    const projectName = req.params.projectName;
    user.status(userName, (status) => {
        if (status) {
            user.hasApp(userName, projectName, (hasApp) => {
                if (hasApp) {
                    res.sendStatus(200);
                } else {
                    user.addApp(userName, projectName, (app) => {
                        res.send(app);
                    });
                }
            });
        } else {
            res.sendStatus(403);
        }
    });
});

router.post('/app/:userName/deleteApp/:appId', (req, res) => {
    const userName = req.params.userName;
    user.status(userName, (status) => {
        if (status) {
            user.deleteApp(userName, req.params.appId, () => {
                res.sendStatus(200);
            });
        } else {
            res.sendStatus(403);
        }
    });
});

router.post('/login', (req, res) => {
    const sid = querystring.parse(req.headers.cookie).sid;
    user.login(req.body, sid).then((data) => {

        res.setHeader('Content-Type', 'application/json');
        if (data.sid) {
            res.setHeader('Set-Cookie', `sid=${data.sid}; HttpOnly=true; SameSite=Strict;`);
            // 用完即删
            delete data.sid;
        }
        res.send(JSON.stringify(data));
        console.log(`[${data.name}]登录成功！`);
    }).catch((data) => {
        delete data.sid;
        res.send(JSON.stringify(data));
        console.log(`[${data.name}]登录失败！`);
    });
});

router.post('/logout', (req, res) => {
    const userName = req.body.name;
    user.logout(userName, true);
    res.send(JSON.stringify({ loginStatus: false }));
});

router.post('/application/:appName/open', (req, res) => {
    fs.readFile(path.join(__dirname, `./data/apps/${req.params.appName}/public/index.html`), (err, data) => {
        if (err) {
            res.send('找不到主文件');
        } else {
            res.setHeader('Content-Type', 'text/html');
            res.send(data);
        }
    });
});

user.removeAllVisitors();

// IO 通信
function setIO(io) {
    io.on('connection', (socket) => {

        socket.on('connection', (arg) => {
            console.log(`[${arg.name}]已建立Socket连接！`);
            // 如果没有缓存，即开服务器后第一次登录推送消息
            if(!router.userToSocket.has(arg.name)) {
                router.socketToUser.set(socket, arg);
                router.userToSocket.set(arg.name, socket);
                
                // if (arg.name.indexOf('visitor-') >= 0) {
                //     socket.emit('welcome', {
                //         isFirstTime
                //     });
                // } else {
                //     socket.emit('welcome', {
                //         text: `${arg.name} 欢迎回到Yungo！`
                //     });
                // } 
                // 发送事件，表明这是该用户第一次登录
                socket.emit('welcome', {
                    text: `欢迎使用YunGoo！点击查看更多...`
                });
            }
        });

        socket.on('system/app/save', (arg) => {
            const data = JSON.parse(arg);
            const app = data.app;
            const user = JSON.parse(data.user);

            const filePath = path.join(__dirname, `user/user_${user.name}`);
            tool.dirExists(filePath).then((value) => {

                const writer = fs.createWriteStream(path.join(filePath, 'app.json'));
                writer.write(JSON.stringify(app));

                socket.emit('system/app/save-status', { status: true, type: 'App' });
                console.log(`[${user.name}]数据保存成功！`);
            }).catch((result) => {
                console.log(`[${user.name}]数据保存失败！`);
                socket.emit('system/app/save-status', { status: false, type: 'App' });
            });
        });

        socket.on('disconnect', (arg) => {
            const value = router.socketToUser.get(socket);
            if (value) {
                console.log(`[${value.name}]已断开Socket连接！`);
                user.logout(value.name, false);
            }
        });
    });
}

router.setIO = setIO;

module.exports = router;